﻿using CustomsDocumentOA.Project.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace CustomsDocumentOA.Project.Web.Host.Controllers
{
    public class UpLoadController : ProjectControllerBase
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public UpLoadController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        [HttpPost]
        public string UpLoadFile()
        {

            //var path = Directory.GetCurrentDirectory();
            //path = path + @"/Uploads";//绝对路径
            //string path = Path.Combine(@"C:\CPPTest\wwwroot\UploadFiles", "CallingCard");//服务器盘符地址
            string path = _hostingEnvironment.WebRootPath + @"/Uploads";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            List<string> val = new List<string>();
            for (int i = 0; i < Request.Form.Files.Count; i++)
            {
                var file1 = Request.Form.Files[i];
                var fileName = file1.FileName.Substring(file1.FileName.LastIndexOf(@"\") + 1);
                var extension = fileName?.Substring(fileName.LastIndexOf("."));
                fileName = Guid.NewGuid().ToString("N");
                fileName += extension;
                using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.CreateNew, FileAccess.ReadWrite))
                {
                    file1.OpenReadStream().CopyTo(fs);
                    fs.Flush();
                }
                val.Add(fileName);
            }
            string res = string.Join(",", val.ToArray());
            return res;
        }
     
        [HttpGet]
        public IActionResult DownloadFile(string fileName)
        {
            var filePath = "/Uploads/"+ fileName;
            //var fileName1 = fileName;
            FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + filePath, FileMode.OpenOrCreate);
            fs.Close();
            return File(new FileStream(_hostingEnvironment.WebRootPath + filePath, FileMode.Open), "application/octet-stream", fileName);
        }
    }
}
